//
//  RootViewController.m
//  VTravel
//
//  Created by lanouhn on 16/8/1.
//  Copyright © 2016年 xiaoYu. All rights reserved.
//

#import "RootViewController.h"
/** 引入tableView的表头视图 */
#import "RootTableHeaderView.h"
/** 引入分区表头视图 */
#import "SectionHeaderView.h"
/** 引入第三个分区的按钮区头视图 */
#import "ButtonSectionHeaderView.h"
/** 引入自定义的周边景点cell */
#import "NearByTableViewCell.h"
/** 引入精选旅游目的地cell */
#import "PickDestinationTableViewCell.h"
/** 引入首页列表数据cell */
#import "RootDataListTableViewCell.h"

/** 引入顶部轮播图实体model类 */
#import "RootScrollViewModel.h"
/** 引入邮轮实体model类 */
#import "RootShipModel.h"
/** 引入门票实体model类 */
#import "RootTicketModel.h"
/** 引入游学实体model类 */
#import "RootStudyModel.h"

/** 点击更多进入详情页面 */
#import "SectionHeaderDetailVC.h"
#import "SectionNearByDAetailVC.h"

/** 点击轮播图跳转界面 */
#import "CycleDetailViewController.h"
#import "BannerDetailViewController.h"

/** 点击表头视图上的邮轮按钮 */
#import "ShipViewController.h"
/** 点击表头视图上的旅游度假按钮 */
#import "TravelDetailViewController.h"

/** 引入定位的框架 */
#import <CoreLocation/CoreLocation.h>
/** 引入扫描二维码第三方 */
#import "HCScanQRViewController.h"

/** 点击周边景点cell进入的视图控制器 */
#import "NearByCellClickDetailVC.h"

#pragma mark - 属性
/** 遵循RootTableHeaderViewDelegate */
@interface RootViewController ()<UITableViewDataSource, UITableViewDelegate, RootTableHeaderViewDelegate, CLLocationManagerDelegate>

/** 自定义导航栏的视图 */
@property (nonatomic, strong) UIView *navigationView;
/** 自定义导航栏上的城市按钮 */
@property (nonatomic, strong) UIButton *cityButton;


/** 底部的大的tableView */
@property (strong, nonatomic) IBOutlet UITableView *rootTableView;

/** 轮播图对象 */
@property (nonatomic, strong) SDCycleScrollView *sdcScrollView;
/** 轮播图model数据源数组 */
@property (nonatomic, strong) NSMutableArray *RootScrollViewdataArray;
/** 轮播图图片数组 */
@property (nonatomic, strong) NSMutableArray *RootImagedataArray;

// 公告数据源
/** 公告ID数组 */
@property (nonatomic, strong) NSMutableArray *bannerNewsIdArray;
/** 公告标题数据 */
@property (nonatomic, strong) NSMutableArray *bannerTitleArray;

// 其他数据源
/** 周边景点数据源数组 */
@property (nonatomic, strong) NSMutableArray *nearByArr;
/** 精选目的地数据源数组 */
@property (nonatomic, strong) NSMutableArray *choiceDetiArray;
/** 游轮数据源数组 */
@property (nonatomic, strong) NSMutableArray *shipDataArray;
/** 门票数据源 */
@property (nonatomic, strong) NSMutableArray *ticketDataArray;
/** 游学数据源 */
@property (nonatomic, strong) NSMutableArray *studyDataArray;
/** 标题数据源 */
@property (nonatomic, strong) NSMutableArray *buttonTitleDataArray;

/** 游轮门票游学模块临时数组 */
@property (nonatomic, strong) NSMutableArray *tempArray;

/** 声明属性用来负责定位服务 */
@property (nonatomic, strong) CLLocationManager *locationManager;
/** 负责将经纬度转为具体的位置 */
@property (nonatomic, strong) CLGeocoder *geocoder;

@end

@implementation RootViewController

#pragma mark - 懒加载
// 轮播图数据源
- (NSMutableArray *)RootScrollViewdataArray{
    if (_RootScrollViewdataArray == nil) {
        self.RootScrollViewdataArray = [NSMutableArray array];
    }
    return _RootScrollViewdataArray;
}
- (NSMutableArray *)RootImagedataArray{
    if (_RootImagedataArray == nil) {
        self.RootImagedataArray = [NSMutableArray array];
    }
    return _RootImagedataArray;
}
// 公告数据源
- (NSMutableArray *)bannerNewsIdArray{
    if (_bannerNewsIdArray == nil) {
        self.bannerNewsIdArray = [NSMutableArray array];
    }
    return _bannerNewsIdArray;
}
- (NSMutableArray *)bannerTitleArray{
    if (_bannerTitleArray == nil) {
        self.bannerTitleArray = [NSMutableArray array];
    }
    return _bannerTitleArray;
}
// 其他数据源
- (NSMutableArray *)nearByArr{
    if (_nearByArr == nil) {
        self.nearByArr = [NSMutableArray array];
    }
    return _nearByArr;
}
- (NSMutableArray *)choiceDetiArray{
    if (_choiceDetiArray == nil) {
        self.choiceDetiArray = [NSMutableArray array];
    }
    return _choiceDetiArray;
}
- (NSMutableArray *)shipDataArray{
    if (_shipDataArray == nil) {
        self.shipDataArray = [NSMutableArray array];
    }
    return _shipDataArray;
}
- (NSMutableArray *)ticketDataArray{
    if (_ticketDataArray == nil) {
        self.ticketDataArray = [NSMutableArray array];
    }
    return _ticketDataArray;
}
- (NSMutableArray *)studyDataArray{
    if (_studyDataArray == nil) {
        self.studyDataArray = [NSMutableArray array];
    }
    return _studyDataArray;
}
- (NSMutableArray *)buttonTitleDataArray{
    if (_buttonTitleDataArray == nil) {
        self.buttonTitleDataArray = [NSMutableArray array];
    }
    return _buttonTitleDataArray;
}
- (CLGeocoder *)geocoder{
    if (_geocoder == nil) {
        self.geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

#pragma mark - 视图加载完成
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 请求轮播图数据
        [self requestScrollViewData];
        // 请求公告数据
        [self requestBannerData];
        // 请求周边景点,游轮.门票,精选旅游目的地等等数据
        [self requestAllData];
    });
    
    // 设置定位
    [self CoreLocation];

    // 创建自定义导航栏
    [self creatNavigationBar];
    
    // 创建表头视图
    [self creatTableHeaderView];
    
    // 注册自定义的周边景点cell
    [self.rootTableView registerNib:[UINib nibWithNibName:@"NearByTableViewCell" bundle:nil] forCellReuseIdentifier:@"NearByTableViewCell"];
    // 注册自定义的精选旅游目的地cell
    [self.rootTableView registerNib:[UINib nibWithNibName:@"PickDestinationTableViewCell" bundle:nil] forCellReuseIdentifier:@"PickDestinationTableViewCell"];
    // 注册自定义的首页列表数据cell
    [self.rootTableView registerNib:[UINib nibWithNibName:@"RootDataListTableViewCell" bundle:nil] forCellReuseIdentifier:@"RootDataListTableViewCell"];
}

#pragma mark - 请求轮播图数据
- (void)requestScrollViewData{
    [NetWorkManager requestForGETWithURL:kROOT_SCROLLVIEW_URL paramater:@{} success:^(id responseObject) {
        
        for (NSDictionary *dic in responseObject) {
            RootScrollViewModel *model = [[RootScrollViewModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            model.goto_ = dic[@"goto"];
            model.desc = dic[@"description"];
            
            [self.RootImagedataArray addObject:ImageURL(model.src)];
            [self.RootScrollViewdataArray addObject:model];
        }
        // 设置轮播图展示的数据源
        self.sdcScrollView.imageURLStringsGroup = self.RootImagedataArray;
        
    } fail:^(NSError *error) {
        
    }];
}
#pragma mark - 请求公告数据
- (void)requestBannerData{
    
    [NetWorkManager requestForGETWithURL:kROOT_BANNER_URL paramater:nil success:^(id responseObject) {
        
        NSArray *tempArray = responseObject[@"data"];
        for (NSDictionary *tempDic in tempArray) {
            [self.bannerNewsIdArray addObject:tempDic[@"news_id"]];
            [self.bannerTitleArray addObject:tempDic[@"title"]];
        }
    } fail:^(NSError *error) {
    }];
}
#pragma mark -  请求周边景点,游轮.门票,精选旅游目的地等等数据
- (void)requestAllData{
    [NetWorkManager requestForGETWithURL:kROOT_ALLDATA_URL paramater:@{@"assistant_id":@"0",@"city_id":city_id} success:^(id responseObject) {
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            // 周边景点
            NSArray *tempArray = responseObject[@"data"][@"aroundScenicList"];
            for (NSDictionary *dic in tempArray) {
                // 因为周边景点的model数据类型跟scrollView的model一样,可以直接使用scrollView的model
                RootScrollViewModel *model = [[RootScrollViewModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                model.src = ImageURL(dic[@"src"]);
                [self.nearByArr addObject:model];
            }
            // 精选旅游目的地数据封装
            NSArray *tempArray1 = responseObject[@"data"][@"choiceDestList"];
            for (NSDictionary *dic in tempArray1) {
                // 精选旅游目的地也才用scrollView的model
                RootScrollViewModel *model = [[RootScrollViewModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                model.src = ImageURL(dic[@"src"]);
                [self.choiceDetiArray addObject:model];
            }
            // 游轮 门票 游学
            NSArray *tempArray2 = responseObject[@"data"][@"productTabList"];
            for (NSDictionary *dic in tempArray2) {
                // 如果三个字典中的list数据不为空时,才封装
                if ([dic[@"list"] count] != 0) {
                    // 添加button到数据源数组
                    [self.buttonTitleDataArray addObject:dic[@"title"]];
                    // 判断确定数据源存放的位置
                    if ([dic[@"title"] isEqualToString:@"邮轮"]) {
                        // 遍历数据进行封装
                        for (NSDictionary *tempDic in dic[@"list"]) {
                            RootShipModel *model = [[RootShipModel alloc] init];
                            [model setValuesForKeysWithDictionary:tempDic];
                            [self.shipDataArray addObject:model];
                        }
                        // 设置默认显示的数据
                        self.tempArray = self.shipDataArray;
                    }else if ([dic[@"title"] isEqualToString:@"门票"]){
                        // 遍历数据进行封装
                        for (NSDictionary *tempDic in dic[@"list"]) {
                            RootTicketModel *model = [[RootTicketModel alloc] init];
                            [model setValuesForKeysWithDictionary:tempDic];
                            [self.ticketDataArray addObject:model];
                        }
                    }else if ([dic[@"title"] isEqualToString:@"游学"]){
                        // 遍历数据进行封装
                        for (NSDictionary *tempDic in dic[@"list"]) {
                            RootStudyModel *model = [[RootStudyModel alloc] init];
                            [model setValuesForKeysWithDictionary:tempDic];
                            [self.studyDataArray addObject:model];
                        }
                    }
                }
            }
        });
        // 刷新数据
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.rootTableView reloadData];
        });
    } fail:^(NSError *error) {
        kMyLog(@"%@", error);
    }];
}

#pragma mark - 创建自定义的导航栏
- (void)creatNavigationBar{
    self.navigationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    self.navigationView.backgroundColor = [UIColor colorWithWhite:1 alpha:0];
    [self.navigationController.navigationBar addSubview:self.navigationView];
    // 将自定义的导航栏放在最上面
    [self.navigationController.navigationBar bringSubviewToFront:self.navigationView];
    // 设置导航栏的样式
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    // 设置透明的背景图
    [self.navigationController.navigationBar setBackgroundImage:[self drawPngImageWithAlpha:0] forBarMetrics:(UIBarMetricsDefault)];
    // 清除导航栏下的黑线
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];

    // 城市按钮
    self.cityButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.cityButton.frame = CGRectMake(0, 0, 90, 44);
    [self.cityButton setTitle:@"城市" forState:(UIControlStateNormal)];
    [self.cityButton setTitleColor:[UIColor orangeColor] forState:(UIControlStateNormal)];
    self.cityButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.cityButton setImage:[UIImage imageNamed:@"矩形-36"] forState:(UIControlStateNormal)];
    [self.cityButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 20)];
    [self.cityButton setImageEdgeInsets:UIEdgeInsetsMake(0, 70, 0, 0)];
    [self.cityButton addTarget:self action:@selector(handleButtonClickAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.navigationView addSubview:self.cityButton];
    
    // 创建二维码按钮
    UIButton *QRCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    QRCodeButton.frame = CGRectMake(kScreenWidth - 45, 0, 40, 40);
    [QRCodeButton setImage:[UIImage imageNamed:@"扫一扫-副本"] forState:(UIControlStateNormal)];
    [QRCodeButton addTarget:self action:@selector(ClickQRCodeButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.navigationView addSubview:QRCodeButton];
    
    // 创建搜索输入框
    UITextField *searchTF = [[UITextField alloc] initWithFrame:CGRectMake(90, 5, kScreenWidth - 90 - 45, 30)];
    searchTF.layer.cornerRadius = 5;
    searchTF.layer.borderWidth = 1;
    searchTF.layer.borderColor = [UIColor whiteColor].CGColor;
    searchTF.borderStyle = UITextBorderStyleRoundedRect;
    searchTF.backgroundColor = [UIColor colorWithRed:0.83 green:0.83 blue:0.83 alpha:0.5];
    searchTF.placeholder = @"景区/地区/关键字";
    searchTF.font = [UIFont systemFontOfSize:15];
    // 创建输入框上的图片
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 30, 15)];
    imageView.image = [UIImage imageNamed:@"Search"];
    imageView.contentMode = UIViewContentModeScaleAspectFit; // 设置图片的填充样式
    searchTF.leftView = imageView;
    searchTF.leftViewMode = UITextFieldViewModeAlways;
    [self.navigationView addSubview:searchTF];
}
#pragma mark - 点击城市按钮触发的事件(跳转到城市列表)
- (void)handleButtonClickAction{
    kMyLog(@"跳转到城市列表");
}
#pragma mark - 点击二维码扫描跳转事件
- (void)ClickQRCodeButtonAction{
    kMyLog(@"点击了二维码扫描按钮");
    HCScanQRViewController *scan = [[HCScanQRViewController alloc]init];
    //调用此方法来获取二维码信息
    [scan successfulGetQRCodeInfo:^(NSString *QRCodeInfo) {

    }];
    [self.navigationController pushViewController:scan animated:YES];

    
}

#pragma mark - 创建表头视图
- (void)creatTableHeaderView{
    NSArray *tempArray = @[@"旅游度假", @"目的地参团", @"邮轮", @"签证", @"游学", @"门票"];
    RootTableHeaderView *headerView = [[RootTableHeaderView alloc] initWithRootHeaderViewFrame:CGRectMake(0, 0, kScreenWidth, 370) andBtnTitleArray:tempArray andBannerDataArr:self.bannerTitleArray];
    self.sdcScrollView = headerView.sdcycleScrollView;
    headerView.delegate = self;
    
    [headerView clickBannerBlock:^(NSInteger index) {
        // 进行banner的回调
        kMyLog(@"点击了第%ld个公告", index);
        
        BannerDetailViewController *bannerDVC = [[BannerDetailViewController alloc]init];
        bannerDVC.bannerNews_id = self.bannerNewsIdArray[index];
        bannerDVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:bannerDVC animated:YES];
        
    } andBtnBlock:^(NSInteger index) {
        // 点击了自定义button的回调
        kMyLog(@"点击了%@", tempArray[index]);
        switch (index) {
            case 0:{
                // 跳转到旅游界面
                TravelDetailViewController *travelDVC = [[TravelDetailViewController alloc] init];
                travelDVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:travelDVC animated:YES];
                break;
            }
            case 1:
                
                break;
            case 2:{
                // 跳转到邮轮界面
                ShipViewController *shipVC = [[ShipViewController alloc] init];
                shipVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:shipVC animated:YES];
            }
                break;
            case 3:
                
                break;
            case 4:
                
                break;
            case 5:
                
                break;
                
            default:
                break;
        }
    }];
    self.rootTableView.tableHeaderView = headerView;
}
#pragma Mark- RootTableHeaderViewDelegate代理方法
- (void)clickScrollView:(SDCycleScrollView *)scrollView andIVIndex:(NSInteger)index{
    kMyLog(@"点击了轮播图的第%ld张图片", index + 1);
    // 获取点击的轮播图实体model
    RootScrollViewModel *model = self.RootScrollViewdataArray[index];
    CycleDetailViewController *cycleDVC = [[CycleDetailViewController alloc] init];
    cycleDVC.link = model.link;
    // 设置二级界面标题7
    cycleDVC.title = model.title;
    // 隐藏tabBar
    cycleDVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:cycleDVC animated:YES];
}

#pragma mark - TableView代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
#pragma mark - 返回表视图分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return 1;
            break;
        case 2:{
            if (self.tempArray == self.shipDataArray) {
                return self.shipDataArray.count;
            }else if (self.tempArray == self.ticketDataArray){
                return self.ticketDataArray.count;
            }else if (self.tempArray == self.studyDataArray){
                return self.studyDataArray.count;
            }else{
                return 0;
            }
            break;
        }
        default:
            return 0;
            break;
    }
}
#pragma mark - 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {
        NearByTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NearByTableViewCell" forIndexPath:indexPath];
        cell.ClickedSceneryBtnBlock = ^(NSString *title){
            kMyLog(@"点击了%@", title);
            NearByCellClickDetailVC *detailVC = [[NearByCellClickDetailVC alloc] init];
            detailVC.hidesBottomBarWhenPushed = YES;
            detailVC.TitleStr = title;
            detailVC.type = XYPushTransitionTypeFromRootNearByCells;
            [self.navigationController pushViewController:detailVC animated:YES];
        };
        cell.ClickedStewardBlock = ^(){
            kMyLog(@"跳转到管家页面");
        };
        // 数据源给cell赋值(安全处理)
        if (self.nearByArr.count != 0) {
            cell.nearByModelArray = self.nearByArr;
        }
        return cell;
    }else if (indexPath.section == 1){
        PickDestinationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PickDestinationTableViewCell" forIndexPath:indexPath];
        // 传数组中第一个对象给cell进行展示
        if (self.choiceDetiArray != 0) {
            cell.model = self.choiceDetiArray[0];
        }
        return cell;
    }else{
        RootDataListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RootDataListTableViewCell" forIndexPath:indexPath];
        if (self.tempArray == self.shipDataArray) {
            if (self.shipDataArray.count != 0) {
                cell.shipModel = self.shipDataArray[indexPath.row];
            }
        }else if (self.tempArray == self.ticketDataArray){
            if (self.ticketDataArray.count != 0) {
                cell.ticketModel = self.ticketDataArray[indexPath.row];
            }
        }else if (self.tempArray == self.studyDataArray){
            if (self.studyDataArray.count != 0) {
                cell.studayModel = self.studyDataArray[indexPath.row];
            }
        }
        return cell;
    }
}
#pragma mark - 点击Cell会走的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        PickDestinationTableViewCell *cell = [self.rootTableView cellForRowAtIndexPath:indexPath];
        kMyLog(@"%@", cell.nameLabel.text);
        NearByCellClickDetailVC *detailVC = [[NearByCellClickDetailVC alloc] init];
        detailVC.hidesBottomBarWhenPushed = YES;
        detailVC.TitleStr = cell.nameLabel.text;
        detailVC.type = XYPushTransitionTypeFromRootPickerDestinationCells;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}
#pragma mark - 返回cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.section) {
        case 0:
            return 270;
            break;
        case 1:
            return 120;
            break;
        case 2:
            return 80;
            break;
        default:
            return 0;
            break;
    }
}
#pragma mark - 返回分区区头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    NSString *title = nil;
    if (section == 0) {
        title = @"周边景点";
        SectionHeaderView *sectionHeaderView = [[SectionHeaderView alloc] initWithTitle:title];
        sectionHeaderView.mornBtnClicked = ^(){
            kMyLog(@"%@", title);
            SectionNearByDAetailVC *sectionNearByDVC = [[SectionNearByDAetailVC alloc] init];
            [self.navigationController pushViewController:sectionNearByDVC animated:YES];
        };
        return sectionHeaderView;
    }else if (section == 1){
        title = @"精选旅游目的地";
        SectionHeaderView *sectionHeaderView = [[SectionHeaderView alloc] initWithTitle:title];
        sectionHeaderView.mornBtnClicked = ^(){
            SectionHeaderDetailVC *sectionHeaderDetailVC = [[SectionHeaderDetailVC alloc]init];
            [self.navigationController pushViewController:sectionHeaderDetailVC animated:YES];
        };
        return sectionHeaderView;
    }else{
        ButtonSectionHeaderView *buttonHeaderView = [[ButtonSectionHeaderView alloc] initWithButtonTitleArray:self.buttonTitleDataArray];
        
        buttonHeaderView.BtnClickedBlock = ^(NSInteger index){
            kMyLog(@"%@", self.buttonTitleDataArray[index]);
            

            // ***************
            if ([self.buttonTitleDataArray[index] isEqualToString:@"邮轮"]) {
                self.tempArray = self.shipDataArray;
            }else if ([self.buttonTitleDataArray[index] isEqualToString:@"门票"]){
                self.tempArray = self.ticketDataArray;
            }else if ([self.buttonTitleDataArray[index] isEqualToString:@"游学"]) {
                self.tempArray = self.studyDataArray;
            }
            // 刷新界面
            [self.rootTableView reloadData];
        };
        return buttonHeaderView;
    }
}
#pragma mark - 返回分区区头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return section == 2 ? 44 : 30;
}
#pragma mark - 视图将要出现的方法(将自定义的导航栏展示出来)
- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.translucent = YES;// 高斯模糊效果(毛玻璃效果)
    self.navigationView.hidden = NO;
}
#pragma mark - 视图将要消失的方法(将自定义的导航栏隐藏起来)
- (void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBar.translucent = NO;
    self.navigationView.hidden = YES;
}
#pragma mark - 滚动视图的滚动方法 - 用来在滑动时改变导航栏的透明度
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    // 判断当前滚动的是整体的tableView
    if (scrollView == self.rootTableView) {
        CGFloat y = scrollView.contentOffset.y;
        CGFloat alpha = (y / 200.0) > 1.0 ? 1.0 : (y / 200.0);
        // 设置自定义导航栏的背景图片
        [self.navigationController.navigationBar setBackgroundImage:[self drawPngImageWithAlpha:alpha] forBarMetrics:(UIBarMetricsDefault)];
    }
    // 表视图的粘附效果
    CGFloat sectionHeaderHeight = 30; //这里是我的headerView和footerView的高度
    if (_rootTableView.contentOffset.y<=sectionHeaderHeight&&_rootTableView.contentOffset.y>=0) {
        _rootTableView.contentInset = UIEdgeInsetsMake(-_rootTableView.contentOffset.y, 0, 0, 0);
    } else if (_rootTableView.contentOffset.y>=sectionHeaderHeight) {
        _rootTableView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}
#pragma mark - 设置定位的方法
- (void)CoreLocation{
    // 1.开启用户的授权,允许定位
    // 需要在info.plist文件中设置支持定位的字段
    /*
     NSLocationWhenInUseUsageDescription  在使用期间定位
     NSLocationAlwaysUsageDescription  始终允许定位
     */
    // 2.创建定位管理对象
    self.locationManager = [[CLLocationManager alloc] init];
    // 3.判断手机设置中的定位是否开启
    if (![CLLocationManager locationServicesEnabled]) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url];
        return;
    }
    // 4.判断用户对软件的授权状态.(是否允许此软件定位)
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
        return;
    }
    // 5.开启定位服务
    // 5.1 设置定位的精确度, 精确度越高越耗电
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 5.2 设置最小的更新距离.超过100米,立马再次定位
    self.locationManager.distanceFilter = 100;
    // 5.3 注意:重点,想要获取定位结果,需要代理方法
    self.locationManager.delegate = self;
    // 5.4 开启定位
    [self.locationManager startUpdatingLocation];

}
#pragma  mark - 定位的代理方法CLLocationManagerDelegate
// 1.定位成功, 或者再次定位会执行的方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    // CLLocation 位置对象 (第一个是最新的位置)
    CLLocation *location = [locations firstObject];
    // 获取经纬度
    CLLocationCoordinate2D coordinate = location.coordinate;
    [self getAddressByCoordinate:coordinate];
}
// 2.定位失败
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"定位失败: %@", error);
}
#pragma mark - 通过经纬度获取具体的地标位置 -- 反向地理编码
- (void)getAddressByCoordinate:(CLLocationCoordinate2D)coordinate {
    // 1.先通过传入的经纬度,获取Location对象
    CLLocation *location = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    // 2.开始反向地理编码
    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        // 2.1 获取地标对象
        CLPlacemark *placeMark = [placemarks firstObject];
        // 2.2 所有关于位置的信息都在该字典中
        NSDictionary *dic = placeMark.addressDictionary;
        NSString *city = dic[@"City"];
        [self.cityButton setTitle:city forState:(UIControlStateNormal)];
 
    }];
}

#pragma mark -

@end
